using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.PresentTemplates
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="PresentTemplate"/> instances.
    /// </summary>
    public class PresentTemplateCommandHandler :
        ICommandHandler<EnterPresentTemplate>,
        ICommandHandler<ChangePresentTemplate>,
        ICommandHandler<DeletePresentTemplate>
    {
        private readonly IRepository _repository;

        public PresentTemplateCommandHandler(IRepository repository)
        {
            _repository = repository;
        }

        public void Handle(EnterPresentTemplate command)
        {
            PresentTemplate presentTemplate = new PresentTemplate(command.PresentTemplateId, command.PresentData, command.Comment);
            SavePresentTemplate(presentTemplate);
        }

        public void Handle(ChangePresentTemplate command)
        {
            PresentTemplate presentTemplate = _repository.GetById<PresentTemplate>(command.PresentTemplateId, command.Version);
            presentTemplate.Change(command.PresentData, command.Comment);
            SavePresentTemplate(presentTemplate);
        }

        public void Handle(DeletePresentTemplate command)
        {
            PresentTemplate presentTemplate = _repository.GetById<PresentTemplate>(command.PresentTemplateId, command.Version);
            presentTemplate.Delete();
            SavePresentTemplate(presentTemplate);
        }

        private void SavePresentTemplate(PresentTemplate presentTemplate)
        {
            _repository.Save(presentTemplate, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}